using System.IO;
using Bookvar.ObjectModel;

namespace Bookvar.ServiceModel.Actions
{
    public class DeleteFileResourceAction : ResourcePersistenceAction
    {
        private string fileName;

        public DeleteFileResourceAction( IPersistenceService persistenceService, MindMap mindmap, IFileResource resource )
            : base( persistenceService, mindmap, resource )
        {
        }

        public override void Execute()
        {
            fileName = Path.GetTempFileName();
            using ( FileStream fileStream = new FileStream( fileName, FileMode.OpenOrCreate, FileAccess.Write ) )
            {
                CopyResourceStream( fileStream );
            }

            PersistenceService.RemoveFileResourceFromPersistence( Mindmap.Key, Resource );
        }

        public override void Undo()
        {
            using ( FileStream fileStream = new FileStream( fileName, FileMode.Open, FileAccess.Read ) )
            {
                PersistenceService.SaveFileResourceToPersistence( Mindmap.Key, Resource, fileStream );
            }
        }

        protected override void Dispose(bool disposing)
        {
            if ( disposing )
            {
                if ( File.Exists( fileName ) )
                {
                    File.Delete( fileName );
                }
            }

            base.Dispose( disposing );
        }
    }
}